#! encoding:utf-8

import os
import subprocess
import ConfigParser
import shutil
import time

LOGEL_EXE = "Logel.exe"
HISTORY_DIR = "History"
LOGEL_INI = "logel.ini"
DUMP_FINISHED= 'Dump Finished'

class MyConf(ConfigParser.ConfigParser):
    def __init__(self, defaults=None):
        ConfigParser.ConfigParser.__init__(self, defaults=None, allow_no_value=True)

    def optionxform(self, optionstr):
        return optionstr


class ArmLogController():
    def __init__(self, diag_port, armLogPath, saveLogDir):
        self.pwdpath = armLogPath
        self.saveLogDir = saveLogDir
        self.diag_port = int(str(diag_port)[3:]) if "com" in str(diag_port).lower() else int(diag_port)
        self.pid = 0

        self.armLogExePath = None
        self.armLogIniPath = None
        self.armLogHistoryDir = None

        self.initArmlogPath()
        self.assFileSize = 0

        if self.armLogExePath is None or self.armLogIniPath is None:
            raise Exception("The Logel tool does not exist,Please copy the Logel tool to the current directory!")

    def initArmlogPath(self):

        for path, dirList, fileList in os.walk(self.pwdpath):
            if LOGEL_EXE in fileList:
                self.armLogExePath = os.path.join(path, LOGEL_EXE)
                self.armLogHistoryDir = os.path.join(path, HISTORY_DIR)
            if LOGEL_INI in fileList:
                self.armLogIniPath = os.path.join(path, LOGEL_INI)


    def modifyConfig(self):
        config = MyConf()

        config.read(self.armLogIniPath)

        config.set("Settings", 'Auto Start Logging', '1')
        config.set("Settings", 'AssertCommand', '0,t,z')

        config.set("MS", "AutoIdentifyPort", '0')
        config.set("MS", "Type", '1')
        config.set("MS", "DiagPort", str(self.diag_port))
        config.set("MS", "DiagBaud", "115200")
        config.set("MS", "LogOutputFolder", self.armLogHistoryDir)

        fh = open(self.armLogIniPath, 'w')
        config.write(fh)
        fh.close()

    def removeDir(self, dirPath):
        try:

            shutil.rmtree(dirPath, ignore_errors=True)
        except Exception,e:
            pass

    def copyDir(self, srcDir, dstDir):
        try:
            cmd_copy = 'xcopy "{}" "{}" /s /e /d /y'.format(srcDir, dstDir)
            child2 = subprocess.Popen(cmd_copy, shell=True)
            child2.wait()
        except Exception, e:
            pass

    def moveLog(self):
        self.copyDir(self.armLogHistoryDir, self.saveLogDir)
        self.removeDir(self.armLogHistoryDir)

    def startArmlog(self):
        self.modifyConfig()

        self.removeDir(self.armLogHistoryDir)

        p = subprocess.Popen(self.armLogExePath, shell=False)
        self.pid = p.pid
        time.sleep(2*60)


    def closedArmLog(self):
        os.system("taskkill /pid {} -t -f".format(self.pid))
        self.pid = 0
        # time.sleep(2)

    def checkAssertIsEnd(self):
        for path, dirList, fileList in os.walk(self.armLogHistoryDir):
            assFile = [fileName for fileName in fileList if fileName.endswith(".ass")]
            if len(assFile) == 0:
                continue
            # sizeFile = os.path.getsize(os.path.join(path, assFile[0]))
            # if sizeFile > self.assFileSize:
            #     self.assFileSize = sizeFile
            # else:
            #     return True
            with open(os.path.join(path, assFile[0]), "r") as f:
                for line in f.readlines():
                    if DUMP_FINISHED in line:
                        return True
        return False

    def __del__(self):
        if self.pid > 0:
            self.closedArmLog()
            self.moveLog()
